package com.xie.demo.demo;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @作者：xie
 * @时间：2023/8/18 9:12
 */
public class BotPool extends Thread{
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    private final Queue<Integer> queue = new LinkedList<>();

    AtomicInteger a = new AtomicInteger(0);

    public void add() {
        lock.lock();
        try {
            queue.add(a.incrementAndGet());
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void consume(Integer num){
        System.out.print(num);
    }


    @Override
    public void run() {
        while (true){
            lock.lock();
            if(queue.isEmpty()){
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    lock.unlock();
                    break;
                }
            }else {
                Integer num = queue.remove();
                lock.unlock();
                // 耗时操作，因此要在释放锁之后执行
                consume(num);
            }
        }
    }
}
